/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { AnnotationNamespaceType, ArkAssignStmt, ArkInstanceInvokeExpr, ArkMethod, ArkStaticFieldRef, ArkStaticInvokeExpr, Local, Stmt } from 'arkanalyzer/lib';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Rule, Defects, MatcherTypes, MethodMatcher, MatcherCallback } from '../../Index';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'CryptoReplacementCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: 'docs/crypto-replacement-check.md',
    description: 'Prefer using built-in @ohos.security.cryptoFramework APIs over @ohos/crypto-js APIs.'
};

const cryptoJSSign: string = '@thirdParty/@ohos/crypto-js/index.d.ts: CryptoJS';
const methodNames: string[] = [
    'MD5', 'SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512', 'HmacSHA224',
    'HmacSHA256', 'HmacSHA384', 'HmacSHA512', 'HMAC', 'AES', 'PBKDF2', 'TripleDES',
];

export class CryptoReplacementCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private mtdMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD,
    };

    public registerMatchers(): MatcherCallback[] {
        const matchMethodCb: MatcherCallback = {
            matcher: this.mtdMatcher,
            callback: this.check
        };
        return [matchMethodCb];
    }

    public check = (target: ArkMethod): void => {
        const stmts = target.getBody()?.getCfg().getStmts() ?? [];
        for (let stmt of stmts) {
            if (!(stmt instanceof ArkAssignStmt)) {
                continue;
            }
            let signStr = '';
            let methodName = '';
            const rightOp = stmt.getRightOp();
            if (rightOp instanceof ArkStaticInvokeExpr) {
                signStr = rightOp.getMethodSignature().toString();
                methodName = rightOp.getMethodSignature().getMethodSubSignature().getMethodName();
            }
            if (rightOp instanceof ArkInstanceInvokeExpr) {
                const base = rightOp.getBase();
                if (!(base instanceof Local)) {
                    continue;
                }
                const type = base.getType();
                if (!(type instanceof AnnotationNamespaceType)) {
                    continue;
                }
                signStr = type.getNamespaceSignature().toString();
                methodName = rightOp.getMethodSignature().getMethodSubSignature().getMethodName();
            }
            if (rightOp instanceof ArkStaticFieldRef) {
                signStr = rightOp.getFieldSignature().toString();
                methodName = rightOp.getFieldName();
            }
            if (signStr.startsWith(cryptoJSSign) && methodNames.includes(methodName)) {
                this.reportIssue(stmt, methodName);
            }
        }
    };

    private reportIssue(stmt: Stmt, methodName: string): void {
        const text = stmt.getOriginalText();
        if (!text || text.length === 0) {
            logger.debug('Stmt text is empty.');
            return;
        }
        const index = text.indexOf('.' + methodName);
        if (index === -1) {
            return;
        }
        const severity = this.rule.alert ?? this.metaData.severity;
        const originalPosition = stmt.getOriginPositionInfo();
        const lineNum = originalPosition.getLineNo();
        const startColum = originalPosition.getColNo() + index;
        const endColum = startColum + methodName.length + 1;
        const filePath = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile().getFilePath();
        let defects = new Defects(lineNum, startColum, endColum, this.metaData.description, severity, this.rule.ruleId, filePath,
            this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}